<?php
/**new
**/

import('classes.handler.Handler');
class TMTGHandler extends Handler {
	function TMTGHandler()
	{
	}
	function CN_TMTG($args, &$request) {
		$templateMgr =& TemplateManager::getManager();

		$now = time();
		$Nam = Request::getUserVar("Nam");
		if ($Nam)
			$date1 = mktime(0, 0, 0, 1, 1, $Nam);
		else
			$date1 = time();  
		$templateMgr->assign('ngay', $date1);

		$LoaiTien  = Request::getUserVar("LoaiTien");
		if (!$LoaiTien)
			$LoaiTien = "VND";
		$templateMgr->assign('LoaiTien', $LoaiTien);
		
		$ChiTiet  = Request::getUserVar("ChiTiet");
		if ($ChiTiet)
			$sttChiTiet =substr($ChiTiet,0,1);
		else
			$sttChiTiet = 1;
		$templateMgr->assign(sttChiTiet, $sttChiTiet);


		$router =& $request->getRouter();
		
		$journalDao =& DAORegistry::getDAO('JournalDAO');
		$journalPath = $router->getRequestedContextPath($request);
		$templateMgr->assign('helpTopicId', 'user.home');

		$user =& Request::getUser();
		$xma_dvcs = $user->getPath();

		$templateMgr->assign('gcNam', $gcNam);
		$templateMgr->assign('PhanHe', "CapNhat");
		$templateMgr->assign('CN_SecDetail', "CN_TMTG");
		$templateMgr->assign('CN_Title', "Ti&#7873;n m&#7863;t - Ti&#7873;n g&#7917;i" );
		$templateMgr->assign_by_ref('journal', $journal);
		$newurl = Request::url(null, 'index', 'CN_TMTG');
		$templateMgr->assign(newurl , Request::url(null, 'acctCN', 'CN_TMTG'));

		$dmntDao =& DAORegistry::getDAO('DMNTDAO');
		$dsmant =& $dmntDao->getDSMANT_MA();

		$templateMgr->assign('dmntf', $dsmant );
		$templateMgr->addJavaScript('classes/acct/js/ListCT.js');
		$templateMgr->display('acctCN/TMTG.tpl');
	}


	function CTTMTG($args, &$request) {
		$xMode  = Request::getUserVar("Mode");
		//echo "$xMode   xMode  ";

		if ($xMode !==null)
			$this->edit_createCTTMTG($request->getBaseUrl(), $args);
		else
			$this->listCTTMTG($request->getBaseUrl());

	}

	function CTTMTG_In($args, &$request) {
		import('classes.acct.doiso');
		$idphieu  = Request::getUserVar("idphieu");
		$nam  = Request::getUserVar("nam");
		$noco  = Request::getUserVar("noco");
		$journal =& Request::getJournal();
		$journalid =$journal->getId();

		$query = "SELECT a.soct, a.ngct, a.daidien, a.diachi, a.lydo, a.TK , b.tkdu , b.sotienvn FROM CTTMTG" .$journalid. $nam . " a LEFT JOIN CTTMTG".$journalid.$nam . "CT b ON (a.idphieu = b.idphieu) ";
		
		$query = $query . "WHERE a.idphieu = '". $idphieu ."' " ;
		$ctktDao =& DAORegistry::getDAO('CTTMTGDAO');
        $ctkts =& $ctktDao->getCTKT_ThuChi($query, $noco);
		$sotien = floatval($ctkts[0]["sotienvn"]);
		$bangchu = doiso($sotien);

		$templateMgr =& TemplateManager::getManager();
		$templateMgr->assign('soct', $ctkts[0]["soct"]);
		$templateMgr->assign('ngct', $ctkts[0]["ngct"]);
		$templateMgr->assign('daidien', $ctkts[0]["daidien"]);
		$templateMgr->assign('diachi', $ctkts[0]["diachi"]);
		$templateMgr->assign('lydo', $ctkts[0]["lydo"]);
		$templateMgr->assign('solgctg', $ctkts[0]["solgctg"]);
		if ($noco == "N")
		{
			$templateMgr->assign('tenphieu', "Phiếu Thu");
			$templateMgr->assign('tkno', $ctkts[0]['tk']);
			$templateMgr->assign('tkco', $ctkts[0]['tkdu']);
		}
		else
		{
			$templateMgr->assign('tenphieu', "Phiếu Chi");
			$templateMgr->assign('tkco', $ctkts[0]['tk']);
			$templateMgr->assign('tkno', $ctkts[0]['tkdu']);

		}
		//$templateMgr->assign_by_ref('ctkts', $ctkts);
		$templateMgr->assign('noco', $noco);
		$templateMgr->assign('sotien', $sotien);
		$templateMgr->assign('bangchu', $bangchu);
		$templateMgr->display('acctCN/ThuChi.tpl');
	}

	function listCTTMTG() {
		//newv
		$templateMgr =& TemplateManager::getManager();
		$user =& Request::getUser();
		$userId = $user->getId();
		$journal =& Request::getJournal();
		$journalid =$journal->getId();

		
		$gcNam  = Request::getUserVar("dateExpire1Year");
		$xThang1  = Request::getUserVar("dateExpire1Month");
	
		if ($xThang1)
		{
			$gcNam  = Request::getUserVar("dateExpire1Year");
			$gcNam2  = Request::getUserVar("dateExpire1Year");
			if ($gcNam !=$gcNam2)
			{
				echo '<script type="text/javascript">alert("Chi bao cao trong khoang thoi gian 1 nam"); </script>';
				return;
			}

			$xNgay1  = Request::getUserVar("dateExpire1Day");
			$xThang1  = Request::getUserVar("dateExpire1Month");
			$xNgay2  = Request::getUserVar("dateExpire2Day");
			$xThang2  = Request::getUserVar("dateExpire2Month");
			$date1 = mktime(0, 0, 0, $xThang1, $xNgay1, $gcNam);
			$date2 = mktime(0, 0, 0, $xThang2, $xNgay2, $gcNam);
			$ngay1 = date ( 'Y-m-d', $date1 );
			$ngay2 = date ( 'Y-m-d', $date2 );
		}
		else
		{
			$ngay1  = Request::getUserVar("ngay1");
			$ngay2  = Request::getUserVar("ngay2");
			if ($ngay1)
			{
				$gcNam = substr($ngay1,0,4);
			} 
			else
			{
				$xThang  =date("m", time());//
				$xNgay2  =date("d", time());//
				$xNgay1 = $xNgay2  - 10;
				if ($xNgay1 <=0)
					$xNgay1 = 1;
				$date1 = mktime(0, 0, 0, $xThang, $xNgay1, $gcNam);
				$date2 = mktime(0, 0, 0, $xThang, $xNgay2, $gcNam);
				$ngay1 = date ( 'Y-m-d', $date1 );
				$ngay2 = date ( 'Y-m-d', $date2 );
			}
		}

		$templateMgr->assign('xNam', $gcNam);

		$templateMgr->assign('Date1', $ngay1);  
		$templateMgr->assign('Date2', $ngay2);

		$ctktDao =& DAORegistry::getDAO('CTTMTGDAO');
		$dict = NewDataDictionary($ctktDao->_dataSource);
		$tables = $dict->MetaTables('TABLES', false);
		$tablename = "cttmtg".$journalid. $gcNam;

		if (!in_array($tablename,$tables)) 
		{
			echo '<script type="text/javascript">alert("Khong co du lieu!"); </script>';
			$oldurl= Request::url(null, "index", "CN_TMTG"); 
			Request::redirectUrl($oldurl);
		}


		

		$xChiTiet  = Request::getUserVar("ChiTiet");
		if ($xChiTiet)
		{
			$sttChiTiet =substr($xChiTiet,0,1);
		}
		else
		{
			//$sttChiTiet = Request::getUserVar("sttChiTiet");
		}
		$templateMgr->assign('ChiTiet', $xChiTiet);
		$templateMgr->assign('sttChiTiet', $sttChiTiet);

		$xmant  = 'VND'   ; //Request::getUserVar("mant");
		$templateMgr->assign('loaitien', $xmant);


		//$dmtkDao =& DAORegistry::getDAO('DMTKDAO');
		switch($sttChiTiet)
		{
			case "1":
				$noco = "N";
				$templateMgr->assign('loaiphieu', "Phi&#7871;u Thu");
				$templateMgr->assign('mact', "1-TTM");
				$templateMgr->assign('ma_dk', "PT1");
				$templateMgr->assign('lTK', "TK N&#7907;");
				$templateMgr->assign('lTKDU', "TK C&#243;");
				if ($xmant == "VND")
					$templateMgr->assign('loaitk', "111");
				else
					$templateMgr->assign('loaitk', "111");
				break;
			case "2":
				$noco = "C";
				$templateMgr->assign('loaiphieu', "Phi&#7871;u Chi");
				$templateMgr->assign('mact', "2-CTM");
				$templateMgr->assign('ma_dk', "PC1");
				$templateMgr->assign('lTKDU', "TK N&#7907;");
				$templateMgr->assign('lTK', "TK C&#243;");
				if ($xmant == "VND")
					$templateMgr->assign('loaitk', "111");
				else
					$templateMgr->assign('loaitk', "111");

				break;
			case "3":
				$noco = "N";
				$templateMgr->assign('loaiphieu', "B&#225;o c&#243;/G&#7917;i ti&#7873;n Ng&#226;n h&#224;ng");
				$templateMgr->assign('mact', "3-TTG");
				$templateMgr->assign('ma_dk', "BN1");
				$templateMgr->assign('lTK', "TK N&#7907;");
				$templateMgr->assign('lTKDU', "TK C&#243;");
				if ($xmant == "VND")
					$templateMgr->assign('loaitk', "112");
				else
					$templateMgr->assign('loaitk', "112");

				break;
			case "4":
				$noco = "C";
				$templateMgr->assign('loaiphieu', "B&#225;o n&#7907;/R&#250;t ti&#7873;n Ng&#226;n h&#224;ng");
				$templateMgr->assign('mact', "4-CTG");
				$templateMgr->assign('ma_dk', "BC1");
				$templateMgr->assign('lTKDU', "TK N&#7907;");
				$templateMgr->assign('lTK', "TK C&#243;");
				if ($xmant == "VND")
					$templateMgr->assign('loaitk', "112");
				else
					$templateMgr->assign('loaitk', "112");

				break;
	
		}

		$templateMgr->assign('noco', "N");
		$templateMgr->assign('action', "Chung tu Thang ".$xThang."/".$gcNam);
		// them phan Search
		$searchType = null;
		$searchMatch = null;
		$search = Request::getUserVar('search');
		$searchInitial = Request::getUserVar('searchInitial');
		if (!empty($search)) {
			$searchType = Request::getUserVar('searchField');
			$searchMatch = Request::getUserVar('searchMatch');

		} elseif (!empty($searchInitial)) {
			$searchInitial = String::strtoupper($searchInitial);
			$searchType = USER_FIELD_INITIAL;
			$search = $searchInitial;
		}

		$fieldOptions = Array(
		CTKT_FIELD_TKDU => 'TK &#272;&#244;&#237; &#7913;ng ',
		CTKT_FIELD_SOCT => 'S&#7889; ch&#7913;ng t&#7915; ',
		CTKT_FIELD_DIENGIAI => 'Di&#7877;n gi&#7843;i ',
		CTKT_FIELD_SOTIENVN => 'S&#7889; ti&#7873;n '
			);
		$templateMgr->assign('fieldOptions', $fieldOptions);
		$templateMgr->assign('searchField', $searchType);
		$templateMgr->assign('searchMatch', $searchMatch);
		$templateMgr->assign('search', $search);
		$templateMgr->assign('searchInitial', Request::getUserVar('searchInitial'));
		///
		$searchTypeMap = array(
		CTKT_FIELD_TKDU => 'TKDU',
		CTKT_FIELD_SOCT => 'A.SOCT',
		CTKT_FIELD_DIENGIAI => 'DIENGIAI',
		CTKT_FIELD_SOTIENVN => 'B.SOTIENVN'
		);
		$paramArray = array();
		$searchSql = '';

		if (!empty($search) && isset($searchTypeMap[$searchType])) {
			$fieldName = $searchTypeMap[$searchType];
			switch ($searchMatch) {
				case 'is':
					$searchSql = "AND LOWER($fieldName) = LOWER(?)";
					$paramArray[] = $search;
					break;
				case 'contains':
					$searchSql = "AND LOWER($fieldName) LIKE LOWER(?)";
					$paramArray[] = '%' . $search . '%';
					break;
				case 'startsWith':
					$searchSql = "AND LOWER($fieldName) LIKE LOWER(?)";
					$paramArray[] = $search . '%';
					break;
			}
		}
		$rangeInfo = Handler::getRangeInfo('ctkts');
		$query = "SELECT a.idphieu, a.soct, a.ngct, b.diengiai, a.mant, b.sotien_tygia, a.TK , a.macttk , b.tkdu , b.macttkdu, b.sotiennt, b.sotienvn FROM CTTMTG".$journalid. $gcNam . " a LEFT JOIN CTTMTG".$journalid. $gcNam . "CT b ON (a.idphieu = b.idphieu) ";
		
		$query = $query . "WHERE DATE( a.ngct ) >= '" . $ngay1 . "' && DATE( a.ngct ) <=  '" . $ngay2 . "' && a.mact = '" . $templateMgr->_tpl_vars['mact'] . "' " ; 
		$query = $query . $searchSql;
		$query = $query . " ORDER BY ngct, soct";
		$ctkts =& $ctktDao->getCTKT_viewNT($query, $paramArray, $rangeInfo);	

		$templateMgr->assign_by_ref('ctkts', $ctkts);
		$newurl = Request::url(null, 'acctCN', 'CTTMTG_In', null);
		$templateMgr->assign('urlIn', $newurl );

		$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Edit', 'ChiTiet' => $xChiTiet, 'Nam' => $gcNam, "ngay1"=> $ngay1, 'ngay2'=>$ngay2 ));
		$templateMgr->assign('url', $newurl );

		$newurlRFR = Request::url(null, null, 'CTTMTG', null, array('noco' => $noco, 'ChiTiet' => $xChiTiet, 'Nam' => $gcNam, "ngay1"=> $ngay1, 'ngay2'=>$ngay2 ));
		$templateMgr->assign('urlRFR', $newurlRFR );


		$CN_SecDetail2 ="Xem";
		$templateMgr->assign('CN_SecDetail2', $CN_SecDetail2);
		$templateMgr->assign('CN_SecDetail', "CN_TMTG");
		//$templateMgr->assign('searchSql', $searchSql);

		$templateMgr->addStyleSheet($baseurl.'/styles/dm.css');
		$templateMgr->display('acctCN/CTTMTGList.tpl');
	}


	function createDMTK() {
		$this->editDMTK();
	}

	function RFR_DMDV(){
		
		$journal =& Request::getJournal();
		$journalid =$journal->getId();;

		$dmdvdao =& DAORegistry::getDAO('DMDVDAO');
		$dmdv_initial = Request::getUserVar("dmdv_initial");;
		$dmdvString = $dmdvdao->getSetting($journalid, $dmdv_initial);
		echo $dmdvString ;
	}




//	function getTen_DMTK(){
//		$journal =& Request::getJournal();
//		$journalid =$journal->getId();;
//		$dmtkdao =& DAORegistry::getDAO('DMTKDAO');
//
//		$dmtk_ma = Request::getUserVar("dmtk_matk");
//		if (strlen($dmtk_ma)==0)
//		{
//			echo "";
//			return;
//
//		}
//		$dmtk_ma .= '</a></b>-';
//		$dmtkString = $dmtkdao->getSetting($journalid, 'tracuu');
//		echo between ($dmtk_ma, '<br><b>', $dmtkString );
//
//	}

	


	function edit_createCTTMTG($baseurl, $args)
	{   
		$this->validate();
		$this->setupTemplate(true);
		$journal =& Request::getJournal();
		$journalid =$journal->getId();


		import('classes.acct.form.CTTMTGForm');

		$CTTMTGForm = new CTTMTGForm(!isset($args) || empty($args) ? null : ( $args[0]));

		if ($CTTMTGForm->isLocaleResubmit()) {
			$CTTMTGForm->readInputData();
		} else {
			$CTTMTGForm->initData();
		}
		$templateMgr =& TemplateManager::getManager();

		$user =& Request::getUser();
		$ma_dvcs = $user->getma_dvcs();
		$templateMgr->assign('ma_dvcs',  $ma_dvcs);     // dùng để tra cứu

		$dmtkDao =& DAORegistry::getDAO('DMTKDAO');
		$matkAr = $dmtkDao->getSetting($journalid, 'matk');
		array_unshift($matkAr, "?");
		array_unshift($matkAr, "");
		//var_dump($matkAr);
		
		$templateMgr->assign('matka', $matkAr);

		//$matkDVString = $dmtkDao->getSetting($journalid, 'tkdv');
		//$matkCPString = $dmtkDao->getSetting($journalid, 'tkcp');

		//$templateMgr->assign('dmtks', $dmtkString);
		//$templateMgr->assign('matks', $matkString);
//		$templateMgr->assign('matka', $matkAr);
//		$templateMgr->assign('tkdvs', $matkDVString);
//		$templateMgr->assign('tkcps', $matkCPString);

		
		$dmdvdao =& DAORegistry::getDAO('DMDVDAO');
		//$dmdv_initial = "0";
		//$dmdvString = $dmdvdao->getSetting($journalid, $dmdv_initial);

		$madvAr = $dmdvdao->getSettingMADV($journalid, 'madv');

		array_unshift($madvAr, "");
		$templateMgr->assign('madva',  $madvAr); // dung cho combo

		//$madvAr = $dmdvdao->getSettingList($journalid, 'DMDVList');
		$templateMgr->assign('madvList',  $madvAr);     // dùng để tra cứu


		//$templateMgr->assign('dmdv_initial',  $dmdv_initial);
		//$templateMgr->assign('alphaList', explode(' ', __('common.InitList')));
		//$templateMgr->assign('dmdvs',  $dmdvString);
		//$templateMgr->assign('madvs',  $madvString);
		//$templateMgr->assign('macps',  "");


		$xThang  = Request::getUserVar("dateExpire1Month");
		$xNam  = Request::getUserVar("dateExpire1Year");
		if (!$xNam)
			$xNam = Request::getUserVar("Nam");


		///----------
		$xChiTiet  = Request::getUserVar("ChiTiet");
		$templateMgr->assign('ChiTiet', $xChiTiet);
		$sttChiTiet =substr($xChiTiet,0,1);

		$mant  = Request::getUserVar("mant");
		if (!$mant)
			$mant = "VND";

		$templateMgr->assign('mant', $mant);

		$dmntDao =& DAORegistry::getDAO('DMNTDAO');
		$dsmant =& $dmntDao->getDSMANT_MA();
		$templateMgr->assign('dmntf', $dsmant );


		$dmtkDao =& DAORegistry::getDAO('DMTKDAO');

		switch($sttChiTiet)
		{
			case "1":
				$templateMgr->assign('loaiphieu', "Phi&#7871;u Thu");
				$templateMgr->assign('ma_dk', "PT1");
				$templateMgr->assign('noco', "N");
				$templateMgr->assign('lTK', "TK N&#7907;");
				$templateMgr->assign('lTKDU', "TK C&#243;");
				$dstk =& $dmtkDao->getDSMATK("111");
				break;
			case "2":
				$templateMgr->assign('loaiphieu', "Phi&#7871;u Chi");
				$templateMgr->assign('ma_dk', "PC1");

				$templateMgr->assign('noco', "C");
				$templateMgr->assign('lTKDU', "TK N&#7907;");
				$templateMgr->assign('lTK', "TK C&#243;");
				$dstk =& $dmtkDao->getDSMATK("1111");
				break;
			case "3":
				$templateMgr->assign('loaiphieu', "G&#7917;i ti&#7873;n Ng&#226;n h&#224;ng");
				$templateMgr->assign('ma_dk', "BN1");

				$templateMgr->assign('noco', "N");
				$templateMgr->assign('lTK', "TK N&#7907;");
				$templateMgr->assign('lTKDU', "TK C&#243;");
				$dstk =& $dmtkDao->getDSMATK("112");

				break;
			case "4":
				$templateMgr->assign('loaiphieu', "R&#250;t ti&#7873;n Ng&#226;n h&#224;ng");
				$templateMgr->assign('noco', "C");
				$templateMgr->assign('ma_dk', "BC1");

				$templateMgr->assign('lTKDU', "TK N&#7907;");
				$templateMgr->assign('lTK', "TK C&#243;");
		
				$dstk =& $dmtkDao->getDSMATK("112");
				break;
		}
		$templateMgr->assign('tktien', $dstk);
		$templateMgr->assign('mact', $xChiTiet);
		
		$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Add', 'mant' => $xmant, 'ChiTiet' => $xChiTiet, 'Nam' => $xNam ));
		$templateMgr->assign('url', $newurl );

		$templateMgr->addJavaScript('lib/pkp/js/lib/jquery/plugins/validate/jquery.validate.min.js');
		$templateMgr->addJavaScript('lib/pkp/js/jqueryValidatorI18n.js');

//		$host =  $dmtkDao->_dataSource->host;
//		$username =  $dmtkDao->_dataSource->user;
//		$password  = $dmtkDao->_dataSource->password;
//		$databaseName = $dmtkDao->_dataSource->databaseName;
//		$templateMgr->assign('host', $host);
//		$templateMgr->assign('username', $username);
//		$templateMgr->assign('password', $password);
//		$templateMgr->assign('databaseName', $databaseName);
		$templateMgr->assign('journalid', $journalid);

		$templateMgr->assign('xNam', $xNam);
		$templateMgr->assign('xNamT', $xNam-1);

		/// 
		$xidPhieu  = Request::getUserVar("idPhieu");
		if ($xidPhieu == null)
		{
			$templateMgr->assign('action', "Th&#234;m ch&#7913;ng t&#7915; m&#7899;i");
		}
		else
		{
			$templateMgr->assign('action', "S&#7917;a ch&#7913;ng t&#7915;");
		}
		$xidPhieu  = Request::getUserVar("idPhieu");


		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$mysql = "SELECT MAX(idphieu) as num FROM cttmtg".$journalid. $xNam;
		$result =& $ctDao->retrieve($mysql);
		$row =$result->GetRowAssoc(false);
		$maxidphieu = $row["num"];

		$mysql = "SELECT MIN(idphieu) as num FROM cttmtg".$journalid. $xNam ;
		$result =& $ctDao->retrieve($mysql);
		$row =$result->GetRowAssoc(false);
		$minidphieu = $row["num"];

		$mysql = "SELECT COUNT(idphieu) as num FROM cttmtg".$journalid. $xNam ;
		$result =& $ctDao->retrieve($mysql);
		$row =$result->GetRowAssoc(false);
		$countidphieu = $row["num"];

		if ($xidPhieu  == null)
		{
			$pidPhieu  = $maxidphieu;
		}
		else{
			$pidPhieu  = $xidPhieu;
		}



	if ($countidphieu  <= 1){
			$ctlinks = '<div id="idphieu" style="display:none">'.$pidPhieu.'</div>';
		}
		else{

			$ctlinks = '&nbsp &nbsp';
			if ($pidPhieu > $minidphieu){

				$ctlinks .= '<a href="#" onclick="LoadCT('."'".$pidPhieu."'". ",'', 0)". '"' .  '>&lt;&lt;<a>&nbsp&nbsp;';

				$ctlinks .= '<a href="#" onclick="LoadCT('."'".$pidPhieu."'". ",'', -1)". '"' . '>&lt;</a>&nbsp&nbsp;';
			}
			else{
				$ctlinks .= '&lt;&lt; &nbsp; &nbsp';
			}

			$ctlinks .= 'id: <div id="idphieu" style="display:inline">'.$pidPhieu.'</div>&nbsp &nbsp';
		
			if ($pidPhieu < $maxidphieu){
				//newV
				$ctlinks .= '<a href="#" onclick="LoadCT('."'".$pidPhieu."'". ",'', 1)". '"' .  '>&gt;</a>&nbsp;';
				$ctlinks .= '<a <a href="#" onclick="LoadCT('."'".$pidPhieu."'". ",'', 2)". '"' . '>&gt;&gt;</a>&nbsp;';
			}
			else{
				$ctlinks .=   '&gt; &nbsp;';
			}

		}

		$templateMgr->assign(ctlinks , $ctlinks );
			
		//$ctktDao =& DAORegistry::getDAO('CTTMTGDAO');
		// phuc vu phan tim kiem
		$xThang1  = Request::getUserVar("dateExpire1Month");
		if ($xThang1)
		{
			$xNgay1  = Request::getUserVar("dateExpire1Day");
			$xThang1  = Request::getUserVar("dateExpire1Month");
			$xNgay2  = Request::getUserVar("dateExpire2Day");
			$xThang2  = Request::getUserVar("dateExpire2Month");
			$date1 = mktime(0, 0, 0, $xThang1, $xNgay1, $xNam);
			$date2 = mktime(0, 0, 0, $xThang2, $xNgay2, $xNam);
			$ngay1 = date ( 'Y-m-d', $date1 );
			$ngay2 = date ( 'Y-m-d', $date2 );
		}
		else
		{
			$ngay1  = Request::getUserVar("ngay1");
			$ngay2  = Request::getUserVar("ngay2");
		}
		$searchType = null;
		$searchMatch = null;
		$search = Request::getUserVar('search');
		$searchInitial = Request::getUserVar('searchInitial');
		if (!empty($search)) {
			$searchType = Request::getUserVar('searchField');
			$searchMatch = Request::getUserVar('searchMatch');

		} elseif (!empty($searchInitial)) {
			$searchInitial = String::strtoupper($searchInitial);
			$searchType = USER_FIELD_INITIAL;
			$search = $searchInitial;
		}

		$fieldOptions = Array(
		CTKT_FIELD_TKDU => 'TK &#272;&#244;&#237; &#7913;ng ',
		CTKT_FIELD_SOCT => 'S&#7889; ch&#7913;ng t&#7915; ',
		CTKT_FIELD_DIENGIAI => 'Di&#7877;n gi&#7843;i ',
		CTKT_FIELD_SOTIENVN => 'S&#7889; ti&#7873;n '
			);
		$templateMgr->assign('fieldOptions', $fieldOptions);
		$templateMgr->assign('searchField', $searchType);
		$templateMgr->assign('searchMatch', $searchMatch);
		$templateMgr->assign('search', $search);
		$templateMgr->assign('searchInitial', Request::getUserVar('searchInitial'));
		// Case co tìm kiếm
		$searchTypeMap = array(
		CTKT_FIELD_TKDU => 'TKDU',
		CTKT_FIELD_SOCT => 'A.SOCT',
		CTKT_FIELD_DIENGIAI => 'DIENGIAI',
		CTKT_FIELD_SOTIENVN => 'B.SOTIENVN'
		);
		$paramArray = array();
		$searchSql = '';

		if (!empty($search) && isset($searchTypeMap[$searchType])) {
			$fieldName = $searchTypeMap[$searchType];
			switch ($searchMatch) {
				case 'is':
					$searchSql = "AND LOWER($fieldName) = LOWER(?)";
					$paramArray[] = $search;
					break;
				case 'contains':
					$searchSql = "AND LOWER($fieldName) LIKE LOWER(?)";
					$paramArray[] = '%' . $search . '%';
					break;
				case 'startsWith':
					$searchSql = "AND LOWER($fieldName) LIKE LOWER(?)";
					$paramArray[] = $search . '%';
					break;
			}
		}

		$rangeInfo = Handler::getRangeInfo('ctktL');
		$ctktL = array();
		$query = "SELECT a.idphieu, a.soct, a.ngct, b.diengiai, a.mant, b.sotien_tygia, a.TK , a.macttk , b.tkdu , b.macttkdu, b.sotiennt, b.sotienvn FROM CTTMTG".$journalid. $xNam . " a LEFT JOIN CTTMTG".$journalid. $xNam . "CT b ON (a.idphieu = b.idphieu) ";
		$query = $query . "WHERE DATE( a.ngct ) >= '" . $ngay1 . "' && DATE( a.ngct ) <=  '" . $ngay2 . "' && a.mact = '" . $templateMgr->_tpl_vars['mact'] . "' " ; 

		$query = $query . $searchSql;
		$query = $query . " ORDER BY ngct, soct";
		$ctktL =& $ctDao->getCTKT_viewNT($query, $paramArray, $rangeInfo);
		$templateMgr->assign_by_ref('ctktL', $ctktL);

		if ($xThang1)
		{
			$templateMgr->assign('Date1', $ngay1);  
			$templateMgr->assign('Date2', $ngay2);
			$templateMgr->assign('ModeList', 1);
		}
		else{
			$ngay = date ( 'Y-m-d', time() );
			$templateMgr->assign('Date1', $ngay);  
			$templateMgr->assign('Date2', $ngay);
			$templateMgr->assign('ModeList', 0);

		}

		///





		if ($xidPhieu  !== null)
		{
			
		//$query = "SELECT a.idphieu, a.soct, a.ngct, a.daidien, a.diachi, a.lydo, a.solgctg, b.diengiai, a.mant, b.sotien_tygia, a.TK , a.mact, a.noco, b.sotien_tygia,  b.tkdu , b.macttkdu,  b.sotienvn , b.sotiennt, b.id  FROM CTTMTG".$journalid.$xNam . " a LEFT JOIN CTTMTG".$journalid . $xNam . "CT b ON (a.idphieu = b.idphieu)  where a.idphieu = '". $xidPhieu. "' order by a.idphieu, b.id";

			$query = "SELECT a.*, b.*, c.*  FROM CTTMTG".$journalid.$xNam . " a LEFT JOIN CTTMTG".$journalid . $xNam . "CT b ON a.idphieu = b.idphieu LEFT JOIN CTTMTG".$journalid . $xNam . "THUE c ON a.idphieu = c.idphieu   where a.idphieu = '". $xidPhieu. "' order by a.idphieu, b.id, c.idthue";
			

			$ctkts =&$ctDao->getCTKT_edit($query); 
	//var_dump($query);
			$i=0;
			$aCtkt_tkdu = array();
			$aCtkt_macttkdu = array();
			$aCtkt_sotienvn = array();
			$aCtkt_sotiennt = array();
			$aCtkt_diengiai = array();

			$ngay1  = Request::getUserVar("ngay1");
			$ngay2  = Request::getUserVar("ngay2");

			foreach ($ctkts as $key=>$row)
			{
				if ($i==0)
				{
				/*	$soct = $row["soct"];
					$ngct = $row["ngct"];
					$ngaylapct = $row["ngaylapct"];
					$daidien =  $row["daidien"];
					$diachi= $row["diachi"];
					$lydo = $row["lydo"];
					$noidungthue = $row["noidungthue"];
					$solgctg= $row["solgctg"];

					$makh= $row["makh"];
					$tigia = $row["tigia"];
					$mant= $row["mant"];
					$ma_dk= $row["ma_dk"];
					$matk= $row["tk"];

					$templateMgr->assign('soct', $soct);
					$templateMgr->assign('ngct', $ngct);
					$templateMgr->assign('ngaylapct', $ngaylapct);
					$templateMgr->assign('daidien', $daidien);
					$templateMgr->assign('noidungthue', $noidungthue);
					$templateMgr->assign('diachi', $diachi);
					$templateMgr->assign('lydo', $lydo);
					$templateMgr->assign('solgctg', $solgctg);
					$templateMgr->assign('makh', $makh);
					$templateMgr->assign('tigia', $tigia);
					$templateMgr->assign('mant', $mant);

					$templateMgr->assign('matk', $matk); */


				}
				$i++;
				$aCtkt_tkdu[] = $row["tkdu"];

				$aCtkt_macttkdu[] = trim($row["macttkdu"]);
				$aCtkt_sotienvn[] = $row["sotienvn"];
				$aCtkt_sotiennt[] = $row["sotiennt"];
				$aCtkt_diengiai[] = $row["diengiai"];

			}
			$templateMgr->assign('sodong', $i);
			$sa = implode(",,,", $aCtkt_tkdu);

			$templateMgr->assign('tkduss', $sa);
			$sa = implode(",,,", $aCtkt_macttkdu);

			$templateMgr->assign('macttkduss', $sa);
			$sa = implode(",,,", $aCtkt_sotienvn);

			$templateMgr->assign('sotienvnss', $sa);
			if ($xmant == "VND")
				$templateMgr->assign('sotienntss', -1);
			else
			{
			$sa = implode(",,,", $aCtkt_sotiennt);
			$templateMgr->assign('sotienntss', $sa);
			}


			$sa = implode(",,,", $aCtkt_diengiai);
			$templateMgr->assign('diengiaiss', $sa);
			$templateMgr->assign('Mode', 'edit');
			$templateMgr->assign('idphieu', $xidPhieu);
			
			$CN_SecDetail2 ="Sửa chứng từ";
			//$newurlIns = PKPRequest::getProtocol()."://". PKPRequest::getServerHost().PKPRequest::getBasePath()."/pages/acctCN/u_CTTMTG.php";
			$newurlIns  = Request::url(null, "acctCN", 'Ins_CT');

			$urlMain = Request::url(null, null, 'CTTMTG', null, array('mant' => $xmant, 'noco' =>  $templateMgr->_tpl_vars['noco'], 'loaitk' => $templateMgr->_tpl_vars['loaitk'], 'ChiTiet' => $xChiTiet, 'ChiTiet' => $xChiTiet, 'Nam' => $xNam, "ngay1"=> $ngay1, 'ngay2'=>$ngay2 ));
		}
		else
		{
			$newurlIns = PKPRequest::getProtocol()."://". PKPRequest::getServerHost().PKPRequest::getBasePath()."/pages/acctCN/i_CTTMTG.php";

			$newurlIns  = Request::url(null, "acctCN", 'Ins_CT');


			$urlMain = Request::url(null, null, 'CTTMTG', null, array('mant' => $xmant, 'noco' =>  $templateMgr->_tpl_vars['noco'], 'loaitk' => $templateMgr->_tpl_vars['loaitk'], 'ChiTiet' => $xChiTiet, 'ChiTiet' => $xChiTiet, 'Nam' => $xNam, 'Mode'=> 'add' ));
			$templateMgr->assign('sodong', 3);
			$CN_SecDetail2 ="Thêm mới chứng từ";
			$templateMgr->assign('Mode', 'add');
		}

		$urlS_DMDV = Request::url(null, 'acctCN', 'RFR_DMDV');
		$urlS_getTenDMDV = Request::url(null, 'acctCN', 'getTen_DMDV');
		$urlS_getTenDMTK = Request::url(null, 'acctCN', 'getTen_DMTK');

		//echo $newurlRFR ;
		$newurlIn = Request::url(null, 'acctCN', 'CTTMTG_In', null);
		$templateMgr->assign('urlIn', $newurlIn );


		$templateMgr->assign('idphieu', $xidPhieu);
		$templateMgr->assign('urlIns', $newurlIns);
		$templateMgr->assign('urlS_DMDV', $urlS_DMDV);
		$templateMgr->assign('urlS_getTenDMDV', $urlS_getTenDMDV);
		$templateMgr->assign('urlS_getTenDMTK', $urlS_getTenDMTK);
		$templateMgr->assign('urlMain', $urlMain);
		//echo $urlMain;

		// thêm ngày cho list
		$xThang  =date("m", time());//
		$xNgay2  =date("d", time());//

		$xNgay1 = $xNgay2  - 10;
		if ($xNgay1 <=0)
			$xNgay1 = 1;
		$date1 = mktime(0, 0, 0, $xThang, $xNgay1, $xNam);
		$date2 = mktime(0, 0, 0, $xThang, $xNgay2, $xNam);
		$ngay1 = date ( 'Y-m-d', $date1 );
		$ngay2 = date ( 'Y-m-d', $date2 );
		$templateMgr->assign('ngay1', $ngay1);
		$templateMgr->assign('ngay2', $ngay2);


		$templateMgr->assign('CN_SecDetail', "CN_TMTG");
		$templateMgr->assign('CN_SecDetail2', $CN_SecDetail2);



		$CTTMTGForm->display();
	}

	function getdsidphieu(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();
		$ngay1 = Request::getUserVar('ngay1') ;
		$ngay2 = Request::getUserVar('ngay2') ;
		$mact = Request::getUserVar('ChiTiet') ;
		$Year = Request::getUserVar('Year') ;

		$templateMgr =& TemplateManager::getManager();
		$templateMgr->assign('Year', $Year);

		$searchType = null;
		$searchMatch = null;
		$search = Request::getUserVar('search');
		$searchInitial = Request::getUserVar('searchInitial');
		if (!empty($search)) {
			$searchType = Request::getUserVar('searchField');
			$searchMatch = Request::getUserVar('searchMatch');

		} elseif (!empty($searchInitial)) {
			$searchInitial = String::strtoupper($searchInitial);
			$searchType = USER_FIELD_INITIAL;
			$search = $searchInitial;
		}

		$fieldOptions = Array(
		CTKT_FIELD_TKDU => 'TK &#272;&#244;&#237; &#7913;ng ',
		CTKT_FIELD_SOCT => 'S&#7889; ch&#7913;ng t&#7915; ',
		CTKT_FIELD_DIENGIAI => 'Di&#7877;n gi&#7843;i ',
		CTKT_FIELD_SOTIENVN => 'S&#7889; ti&#7873;n '
			);
		$templateMgr->assign('fieldOptions', $fieldOptions);
		$templateMgr->assign('searchField', $searchType);
		$templateMgr->assign('searchMatch', $searchMatch);
		$templateMgr->assign('search', $search);
		$templateMgr->assign('searchInitial', Request::getUserVar('searchInitial'));
		// Case co tìm kiếm
		$searchTypeMap = array(
		CTKT_FIELD_TKDU => 'TKDU',
		CTKT_FIELD_SOCT => 'A.SOCT',
		CTKT_FIELD_DIENGIAI => 'DIENGIAI',
		CTKT_FIELD_SOTIENVN => 'B.SOTIENVN'
		);
		$paramArray = array();
		$searchSql = '';

		if (!empty($search) && isset($searchTypeMap[$searchType])) {
			$fieldName = $searchTypeMap[$searchType];
			switch ($searchMatch) {
				case 'is':
					$searchSql = "AND LOWER($fieldName) = LOWER(?)";
					$paramArray[] = $search;
					break;
				case 'contains':
					$searchSql = "AND LOWER($fieldName) LIKE LOWER(?)";
					$paramArray[] = '%' . $search . '%';
					break;
				case 'startsWith':
					$searchSql = "AND LOWER($fieldName) LIKE LOWER(?)";
					$paramArray[] = $search . '%';
					break;
			}
		}

		//$rangeInfo = Handler::getRangeInfo('ctktL');
		$ctktL = array();
		$query = "SELECT a.idphieu, a.soct, a.ngct, b.diengiai, a.mant, b.sotien_tygia, a.TK , a.macttk , b.tkdu , b.macttkdu, b.sotiennt, b.sotienvn FROM CTTMTG".$journalid. $Year . " a LEFT JOIN CTTMTG".$journalid. $Year . "CT b ON (a.idphieu = b.idphieu) ";
		$query = $query . "WHERE DATE( a.ngct ) >= '" . $ngay1 . "' && DATE( a.ngct ) <=  '" . $ngay2 . "' && a.mact = '" . $mact . "' " ; 

		$query = $query . $searchSql;
		$query = $query . " ORDER BY ngct, soct";

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$ctktL =& $ctDao->getCTKT_viewNT($query, $paramArray, $rangeInfo);
		$templateMgr->assign_by_ref('ctktL', $ctktL);

		$output = $templateMgr->fetch('acctCN/CTTMTGFormTimKQ.tpl');
		echo $output;
		return;
//		$mysql = "SELECT idphieu  FROM cttmtg".$journalid. $Year;
//		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
//		$result =& $ctDao->retrieve($mysql);
//		$kq= '';
//		while (!$result->EOF) {
//				$row =& $result->getRowAssoc(false);
//				$kq = $row["idphieu"].":::";
//				$result->MoveNext();
//		}
//		echo $kq ;
	}


	function getct(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();
		$mact = Request::getUserVar('ChiTiet') ;
		$Year = Request::getUserVar('Year') ;
		$idphieu = Request::getUserVar('idphieu') ;
		$linkdirect = Request::getUserVar('linkdirect') ;

		$templateMgr =& TemplateManager::getManager();
		$dmtkDao =& DAORegistry::getDAO('DMTKDAO');
		$matkAr = $dmtkDao->getSetting($journalid, 'matk');
		array_unshift($matkAr, "");
		$templateMgr->assign('matka', $matkAr);

		$sttChiTiet =substr($mact,0,1);
		switch($sttChiTiet)
		{
			case "1":
				$templateMgr->assign('loaiphieu', "Phi&#7871;u Thu");
				$templateMgr->assign('ma_dk', "PT1");
				$templateMgr->assign('noco', "N");
				$templateMgr->assign('lTK', "TK N&#7907;");
				$templateMgr->assign('lTKDU', "TK C&#243;");
				$dstk =& $dmtkDao->getDSMATK("111");
				break;
			case "2":
				$templateMgr->assign('loaiphieu', "Phi&#7871;u Chi");
				$templateMgr->assign('ma_dk', "PC1");

				$templateMgr->assign('noco', "C");
				$templateMgr->assign('lTKDU', "TK N&#7907;");
				$templateMgr->assign('lTK', "TK C&#243;");
				$dstk =& $dmtkDao->getDSMATK("1111");
				break;
			case "3":
				$templateMgr->assign('loaiphieu', "G&#7917;i ti&#7873;n Ng&#226;n h&#224;ng");
				$templateMgr->assign('ma_dk', "BN1");

				$templateMgr->assign('noco', "N");
				$templateMgr->assign('lTK', "TK N&#7907;");
				$templateMgr->assign('lTKDU', "TK C&#243;");
				$dstk =& $dmtkDao->getDSMATK("112");

				break;
			case "4":
				$templateMgr->assign('loaiphieu', "R&#250;t ti&#7873;n Ng&#226;n h&#224;ng");
				$templateMgr->assign('noco', "C");
				$templateMgr->assign('ma_dk', "BC1");

				$templateMgr->assign('lTKDU', "TK N&#7907;");
				$templateMgr->assign('lTK', "TK C&#243;");
		
				$dstk =& $dmtkDao->getDSMATK("112");
				break;
		}
		$templateMgr->assign('tktien', $dstk);
		$templateMgr->assign('mact', $xChiTiet);


		$dmdvdao =& DAORegistry::getDAO('DMDVDAO');
		$madvAr = $dmdvdao->getSettingMADV($journalid, 'madv');
		array_unshift($madvAr, "");
		$templateMgr->assign('madva',  $madvAr);

		$dmntDao =& DAORegistry::getDAO('DMNTDAO');
		$dsmant =& $dmntDao->getDSMANT_MA();
		$templateMgr->assign('dmntf', $dsmant );


		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		//
		switch($linkdirect)
		{
			case "1":  // next
				$query = "SELECT a.*, b.diengiai, b.sotien_tygia, b.tkdu , b.macttkdu,  b.sotienvn , b.sotiennt, b.id  FROM CTTMTG".$journalid.$Year . " a LEFT JOIN CTTMTG".$journalid . $Year . "CT b ON (a.idphieu = b.idphieu)  where a.idphieu > '". $idphieu. "' order by a.idphieu ASC, b.id LIMIT 1";	
				$ctkts =& $ctDao->getCTKT_edit($query); 
				$idphieu = $ctkts[0]['idphieu'];


				break;
			case "-1": // pre
				$query = "SELECT a.*, b.diengiai, b.sotien_tygia, b.tkdu , b.macttkdu,  b.sotienvn , b.sotiennt, b.id  FROM CTTMTG".$journalid.$Year . " a LEFT JOIN CTTMTG".$journalid . $Year . "CT b ON (a.idphieu = b.idphieu)  where a.idphieu < '". $idphieu. "' order by a.idphieu DESC,  b.id LIMIT 1";	
				$ctkts =& $ctDao->getCTKT_edit($query); 
				$idphieu = $ctkts[0]['idphieu'];

				break;
			case "0":  //first
				$query = "SELECT a.*, b.diengiai, b.sotien_tygia, b.tkdu , b.macttkdu,  b.sotienvn , b.sotiennt, b.id  FROM CTTMTG".$journalid.$Year . " a LEFT JOIN CTTMTG".$journalid . $Year . "CT b ON (a.idphieu = b.idphieu)  where a.idphieu < '". $idphieu. "' order by a.idphieu ASC,  b.id LIMIT 1";	
				$ctkts =& $ctDao->getCTKT_edit($query); 
				$idphieu = $ctkts[0]['idphieu'];

				break;
			case "2": //last
				$query = "SELECT a.*, b.diengiai, b.sotien_tygia, b.tkdu , b.macttkdu,  b.sotienvn , b.sotiennt, b.id  FROM CTTMTG".$journalid.$Year . " a LEFT JOIN CTTMTG".$journalid . $Year . "CT b ON (a.idphieu = b.idphieu)  where a.idphieu > '". $idphieu. "' order by a.idphieu DESC,  b.id LIMIT 1";
				$ctkts =& $ctDao->getCTKT_edit($query); 
				$idphieu = $ctkts[0]['idphieu'];
				break;
		}
		$query = "SELECT a.*, b.diengiai, b.sotien_tygia, b.tkdu , b.macttkdu,  b.sotienvn , b.sotiennt, b.id  FROM CTTMTG".$journalid.$Year . " a LEFT JOIN CTTMTG".$journalid . $Year . "CT b ON (a.idphieu = b.idphieu)  where a.idphieu = '". $idphieu. "' order by b.id";

		$ctkts =& $ctDao->getCTKT_edit($query); 
		$templateMgr->assign_by_ref('ctkts', $ctkts);


		// ctlinks
		$mysql = "SELECT MAX(idphieu) as num FROM cttmtg".$journalid. $Year;
		$result =& $ctDao->retrieve($mysql);
		$row =$result->GetRowAssoc(false);
		$maxidphieu = $row["num"];

		$mysql = "SELECT MIN(idphieu) as num FROM cttmtg".$journalid. $Year ;
		$result =& $ctDao->retrieve($mysql);
		$row =$result->GetRowAssoc(false);
		$minidphieu = $row["num"];

		$mysql = "SELECT COUNT(idphieu) as num FROM cttmtg".$journalid. $Year ;
		$result =& $ctDao->retrieve($mysql);
		$row =$result->GetRowAssoc(false);
		$countidphieu = $row["num"];

		if ($idphieu  == null)
		{
			$pidPhieu  = $maxidphieu;
		}
		else{
			$pidPhieu  = $idphieu;
		}


		if ($countidphieu  <= 1){
			$ctlinks = '<div id="idphieu" style="display:none">'.$pidPhieu.'</div>';
		}
		else{

			$ctlinks = '&nbsp &nbsp';
			if ($pidPhieu > $minidphieu){

				$ctlinks .= '<a href="#" onclick="LoadCT('."'".$pidPhieu."'". ",'', 0)". '"' .  '>&lt;&lt;<a>&nbsp&nbsp;';

				$ctlinks .= '<a href="#" onclick="LoadCT('."'".$pidPhieu."'". ",'', -1)". '"' . '>&lt;</a>&nbsp&nbsp;';
			}
			else{
				$ctlinks .= '&lt;&lt; &nbsp; &nbsp';
			}

			$ctlinks .= 'id: <div id="idphieu" style="display:inline">'.$pidPhieu.'</div>&nbsp &nbsp';
		
			if ($pidPhieu < $maxidphieu){
				//newV
				$ctlinks .= '<a href="#" onclick="LoadCT('."'".$pidPhieu."'". ",'', 1)". '"' .  '>&gt;</a>&nbsp;';
				$ctlinks .= '<a <a href="#" onclick="LoadCT('."'".$pidPhieu."'". ",'', 2)". '"' . '>&gt;&gt;</a>&nbsp;';
			}
			else{
				$ctlinks .=   '&gt; &nbsp;';
			}

		}
		//
		$urlS_getTenDMDV = Request::url(null, 'acctCN', 'getTen_DMDV');
		$urlS_getTenDMTK = Request::url(null, 'acctCN', 'getTen_DMTK');
		$templateMgr->assign('urlS_getTenDMDV', $urlS_getTenDMDV);
		$templateMgr->assign('urlS_getTenDMTK', $urlS_getTenDMTK);



		$output = $templateMgr->fetch('acctCN/CTTMTGFormMainEdit.tpl');
		$output2 = $templateMgr->fetch('acctCN/CTTMTGFormCTEdit.tpl');
		$output3 = $templateMgr->fetch('acctCN/CTTMTGFormThueEdit.tpl');
		echo $ctlinks.":::::".$output.":::::".$output2.":::::".$output3;
		return;
	}

function getmaxidphieu(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();
		$Year = Request::getUserVar('year') ;

		$mysql = "SELECT MAX(idphieu) as num FROM cttmtg".$journalid. $Year;

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$result =& $ctDao->retrieve($mysql);

		$row =$result->GetRowAssoc(false);
		$idphieu = $row["num"];

		echo $idphieu;
	}

	function getmaxidphieu1(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();
		$Year = Request::getUserVar('year') ;
		$show = Request::getUserVar('show') ;

		$mysql = "SELECT MAX(idphieu) as num, mact, ngct, mant FROM cttmtg".$journalid. $Year;

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$result =& $ctDao->retrieve($mysql);

		$row =$result->GetRowAssoc(false);
		$idphieu = $row["num"];
		$xChiTiet = $row["mact"];
		$xmant = $row["mant"];


		//$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Edit', 'mant' => $xmant,  'ChiTiet' => $xChiTiet, 'Nam' => $Year, "ngay1"=> $ngay1, 'ngay2'=>$ngay2 ));

		$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Edit', 'idPhieu' => $idphieu, 'mant' => $xmant,  'ChiTiet' => $xChiTiet, 'Nam' => $Year));

		if ($show == 1){
			Request::redirectUrl($newurl);
		}
		else{
			echo $newurl;
		}
	}


	function getminidphieu(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();
		$Year = Request::getUserVar('year') ;
		$show = Request::getUserVar('show') ;

		$mysql = "SELECT MIN(idphieu) as num FROM cttmtg".$journalid. $Year;

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$result =& $ctDao->retrieve($mysql);

		$row =$result->GetRowAssoc(false);
		$idphieu = $row["num"];

		echo $idphieu;
	}

	function getminidphieu1(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();
		$Year = Request::getUserVar('year') ;
		$show = Request::getUserVar('show') ;

		$mysql = "SELECT MIN(idphieu) as num, mact, ngct, mant FROM cttmtg".$journalid. $Year;

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$result =& $ctDao->retrieve($mysql);

		$row =$result->GetRowAssoc(false);
		$idphieu = $row["num"];
		$xChiTiet = $row["mact"];
		$xmant = $row["mant"];


		//$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Edit', 'mant' => $xmant,  'ChiTiet' => $xChiTiet, 'Nam' => $Year, "ngay1"=> $ngay1, 'ngay2'=>$ngay2 ));

		$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Edit', 'idPhieu' => $idphieu, 'mant' => $xmant,  'ChiTiet' => $xChiTiet, 'Nam' => $Year));

		if ($show == 1){
			Request::redirectUrl($newurl);
		}
		else{
			echo $newurl;
		}
	}

	function getnextidphieu(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();

		$Year = Request::getUserVar('year') ;
		$idphieu = Request::getUserVar('idphieu') ;

		$mysql = "SELECT MIN(idphieu) as num FROM cttmtg".$journalid. $Year. " where idphieu > ". $idphieu;

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$result =& $ctDao->retrieve($mysql);

		$row =$result->GetRowAssoc(false);
		$idphieu = $row["num"];
		echo $idphieu ;
	}

	function getnextidphieu1(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();

		$Year = Request::getUserVar('year') ;
		$show = Request::getUserVar('show') ;
		$idphieu = Request::getUserVar('idphieu') ;

		$mysql = "SELECT MIN(idphieu) as num, mact, ngct, mant FROM cttmtg".$journalid. $Year. " where idphieu > ". $idphieu;

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$result =& $ctDao->retrieve($mysql);

		$row =$result->GetRowAssoc(false);
		$idphieu = $row["num"];
		$xChiTiet = $row["mact"];
		$xmant = $row["mant"];


		//$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Edit', 'mant' => $xmant,  'ChiTiet' => $xChiTiet, 'Nam' => $Year, "ngay1"=> $ngay1, 'ngay2'=>$ngay2 ));

		$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Edit', 'idPhieu' => $idphieu, 'mant' => $xmant,  'ChiTiet' => $xChiTiet, 'Nam' => $Year));

		if ($show == 1){
			Request::redirectUrl($newurl);
		}
		else{
			echo $newurl;
		}
	}

	function getprevidphieu(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();
		$Year = Request::getUserVar('year') ;
		$idphieu = Request::getUserVar('idphieu') ;

		$mysql = "SELECT MAX(idphieu) as num FROM cttmtg".$journalid. $Year. " where idphieu < ". $idphieu;

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$result =& $ctDao->retrieve($mysql);

		$row =$result->GetRowAssoc(false);
		$idphieu = $row["num"];
		echo $idphieu ;
	}

	function getprevidphieu1(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();

		$Year = Request::getUserVar('year') ;
		$show = Request::getUserVar('show') ;
		$idphieu = Request::getUserVar('idphieu') ;

		$mysql = "SELECT MAX(idphieu) as num, mact, ngct, mant FROM cttmtg".$journalid. $Year. " where idphieu < ". $idphieu;

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$result =& $ctDao->retrieve($mysql);

		$row =$result->GetRowAssoc(false);
		$idphieu = $row["num"];
		$xChiTiet = $row["mact"];
		$xmant = $row["mant"];


		//$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Edit', 'mant' => $xmant,  'ChiTiet' => $xChiTiet, 'Nam' => $Year, "ngay1"=> $ngay1, 'ngay2'=>$ngay2 ));

		$newurl = Request::url(null, null, 'CTTMTG', null, array('Mode' => 'Edit', 'idPhieu' => $idphieu, 'mant' => $xmant,  'ChiTiet' => $xChiTiet, 'Nam' => $Year));

		if ($show == 1){
			Request::redirectUrl($newurl);
		}
		else{
			echo $newurl;
		}
	}


	function delect(){
		$journal =& Request::getJournal();
		$journalid =$journal->getId();
		$Year = Request::getUserVar('Year') ;
		$idphieu = Request::getUserVar('idphieu') ;

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		$mysql = "DELETE FROM cttmtg".$journalid. $Year. " where idphieu = '". $idphieu."' LIMIT 1;";


		$mysql2 = "DELETE FROM cttmtg".$journalid. $Year. "ct where idphieu = '". $idphieu."' LIMIT 50";

		$mysql3 = "DELETE FROM cttmtg".$journalid. $Year. "thue where idphieu = '". $idphieu."' LIMIT 50;";
		
		$result =& $ctDao->retrieve($mysql);
		$result =& $ctDao->retrieve($mysql2);
		$result =& $ctDao->retrieve($mysql3);
		echo "1";
	}

	function Ins_CT(){
		//dataMain: dataMain, fieldMain: fieldMain, dataCT: dataCT, fieldCT: fieldCT, mact:mact, noco:noco, idphieu: idphieu
		$journalid = Request::getUserVar('journalid') ;
		$Year = Request::getUserVar('year') ;
		$mact = Request::getUserVar('mact') ;

		$noco = Request::getUserVar('noco') ;
		$idphieu = Request::getUserVar('idphieu') ;
		$addmode  = Request::getUserVar("addmode");

		$tableMain = "cttmtg";
		$user =& Request::getUser();
		$userName = $user->getFullName();



		// kiểm tra file:
		$cttmtgDao =& DAORegistry::getDAO('CTTMTGDAO');
		$dict = NewDataDictionary($cttmtgDao->_dataSource);
		$tables = $dict->MetaTables('TABLES', false);
		$tablename = $tableMain.$journalid. $Year;
		if (!in_array($tablename,$tables)) 
		{
			$cttmtgDao ->CreateTable($Year, $journalid );
		}

		$columns = $dict->MetaColumns($tablename);
		$colnames = array();
		$coltypes = array();
		foreach ($columns as $column) {
			$colnames[] = $column->name;
			$coltypes[] = $column->type;

		}


		$dataMain = Request::getUserVar("dataMain");
		$fieldMain = Request::getUserVar("fieldMain");

		$codulieu = 0;
		$succ = 1;
		$mysql = array();
		$i = 0;
		
		if ($addmode == "add"){
			$mysqlMain = "INSERT INTO ".$tableMain.$journalid. $Year. " SET mact = '$mact', noco = '$noco',user_name0 = '$userName'" ;

		}
		else{
			$mysqlMain = "UPDATE ".$tableMain.$journalid. $Year. " SET user_name1 = '$userName'" ;

		}

		foreach ($dataMain as $key=>$value) {
			$fdulieu = "$value";
			if (!in_array(strtolower($fieldMain[$key]),$colnames)) 
			{
				continue;
			}

			if (strpos($mysqlMain, $fieldMain[$key]) <=0){  // field 0 trungf
				if ($fdulieu)
				{	
					if(preg_match('/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',$value)){
						$dt1   = substr($value,0,2);
						$mon1  = substr($value,3,2);
						$yr1   = substr($value,6);
						$value = "$yr1-$mon1-$dt1";
					}
					$mysqlMain .= ", ". $fieldMain[$key]."  = '".$value."'";
					
				}

			}
		}

		if ($addmode == "edit")
			$mysqlMain .= " WHERE idphieu='". $idphieu . "'";

		$ctDao =& DAORegistry::getDAO('CTTMTGDAO');
		echo $mysqlMain;
		$result =& $ctDao->retrieve($mysqlMain);


		
		if ($addmode == "add") // them moi
		{
			$result =& $ctDao->retrieve("SELECT MAX(idPhieu) as idPhieu FROM ".$tableMain.$journalid. $Year);
			$newidPhieus =$result->GetRowAssoc(false);
			$idphieu = $newidPhieus["idphieu"];

		}
		else
		{
			$mysqld = "DELETE FROM ".$tableMain.$journalid. $Year. "ct WHERE idphieu = '". $idphieu."'";
			$result =& $ctDao->retrieve($mysqld);
		}


		$dataCT = Request::getUserVar("dataCT");
		$fieldCT = Request::getUserVar("fieldCT");

		$columnsct = $dict->MetaColumns($tablename."ct");
		$colnamesct = array();
		$coltypesct = array();
		foreach ($columnsct as $column) {
			$colnamesct[] = $column->name;
			$coltypesct[] = $column->type;
		}

		$mysql = array();
		$i = 0;
		foreach ($dataCT as $v) {
			$mysql[$i] = "INSERT INTO ".$tableMain.$journalid. $Year. "ct SET idPhieu='". $idphieu. "'";
			$codl = null;

			foreach ($v as $key=>$value) 
			{
				$fdulieu = "$value";

				if (!in_array(strtolower($fieldCT[$key]),$colnamesct)) 
				{
					continue;
				}

				if ($fdulieu)
				{		$mysql[$i] .= ", ". $fieldCT[$key]."  = '".$value."'";
						$codl = true;
				}
			}
					echo "<br> $mysql[$i]";
			if ($codl){
				$result =& $ctDao->retrieve($mysql[$i]);
				$i++;

			}

		}

        //---------nhat -----
        //thue
        $dataThue = Request::getUserVar("dataThue");
        $fieldThue = Request::getUserVar("fieldThue");
        $columnsctt = $dict->MetaColumns($tablename."thue");
        $colnamesctt = array();
        $coltypesctt = array();
        foreach ($columnsctt as $columnt) {
            $colnamesctt[] = $columnt->name;
            $coltypesctt[] = $columnt->type;
        }
        $mysql = array();
        $i=0;
        foreach ($dataThue as $v) {
            $mysql[$i] = "INSERT INTO ".$tableMain.$journalid. $Year. "thue SET idPhieu='". $idphieu. "'";
            $codl = null;

            foreach ($v as $key=>$value)
            {
                $fdulieu = "$value";

                if (!in_array(strtolower($fieldThue[$key]),$colnamesctt))
                {
                    continue;
                }

                if ($fdulieu)
                {		$mysql[$i] .= ", ". $fieldThue[$key]."  = '".$value."'";
                    $codl = true;
                }
            }
            if ($codl){
                $result =& $ctDao->retrieve($mysql[$i]);
                $i++;

            }

        }
        //---------end--------------



		echo $mact.":::".$idphieu;

	}
}

/**
 * @file TMTGHandler.inc.php
 * Copyright (c) 2003-2012 John Willinsky
 * Copyright (c) VTN.Diep 2014...
 */


?>
